package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.NameUtil;
import com.kaixinff.name.User;
import com.kaixinff.net.NameValuePair;

@SuppressWarnings("serial")
public class AddFriendServlet extends HttpServlet {
	private static String norect = "1";
	private static String ADD_URL = "http://www.kaixin001.com/friend/new.php?touid=" + KXUtil.getMainUserUid();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.REG_KX) && !user.hasStep(RegStep.ADD_FRIEND_REQUEST);
			}}, resp);
		if (users == null) {
			return;
		}
		
		List<User> us = new ArrayList<User>();
		List<Integer> flags = new ArrayList<Integer>();
		for (User user: users) {
			KXClient client = KXClient.getInstance(user.getId());
			String html = client.doGet(ADD_URL, null).getContent();
			Pattern p = Pattern.compile("var flag = parseInt[(]\"(\\d+?)\"[)];");
			Matcher m = p.matcher(html);
			if (m.find()) {
				int flag = Integer.parseInt(m.group(1));
				if (flag == 0) {
					flag = post(users, user, null, null);
				} 
				if (flag != 0) {
					us.add(user);
					flags.add(flag);
				}
			}
		}
		if (us.size() > 0) {
			get(resp, us, flags);
		}
	}
	
	private void get(HttpServletResponse resp, List<User> users, List<Integer> flags) throws IOException {
		resp.getWriter().println("<form name='form' method='post' action='/kx/addfriend'>");
		for (int i = 0, n = users.size(); i < n; i++) {
			User user = users.get(i);
			int flag = flags.get(i);
			if (flag == 2) {
				resp.getWriter().println("验证码错误，请重新输入！<br>");
			}
			String rcode = Math.random() + "_" + System.currentTimeMillis();
			String imgUrl = "/interface/createwavecaptcha.php?norect=" + norect + "&randnum="
					+ rcode + "&cookiekey=" + user.getId();
			resp.getWriter().println("<input type=hidden name='cookiekey' value='" + user.getId() + "'>" + user.getId());
			resp.getWriter().println("<input type=hidden name='rcode' value='" + rcode + "'>");
			resp.getWriter().println("<input type=text name='code' value=''>");
			resp.getWriter().println("<img src='" + imgUrl + "' /><br>");
		}
		resp.getWriter().println("<input type=submit name='submit' value='go'>");
		resp.getWriter().println("</form>");
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers();
		Map<String, User> userMap = new HashMap<String, User>();
		String[] emails = req.getParameterValues("cookiekey");
		String[] rcodes = req.getParameterValues("rcode");
		String[] codes = req.getParameterValues("code");
		List<User> us = new ArrayList<User>();
		List<Integer> flags = new ArrayList<Integer>();
		for (int i = 0, n = emails.length; i < n; i++) {
			User user = userMap.get(emails[i]);
			int flag = post(users, user, rcodes[i], codes[i]);
			if (flag != 0) {
				us.add(user);
				flags.add(flag);
			}
		}
		if (us.size() > 0) {
			get(resp, us, flags);
		}
	}
	
	private int post(List<User>users, User user, String rcode, String code) throws IOException {
		int flag = 0;
		String url = "http://www.kaixin001.com/friend/addverify.php";
		KXClient client = KXClient.getInstance(user.getId());
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new NameValuePair("from", ""));
		params.add(new NameValuePair("touid", KXUtil.getMainUserUid()));
		params.add(new NameValuePair("content", "哈罗小饭，我是"  + user.getName()));
		if (rcode != null) {
			params.add(new NameValuePair("rcode", rcode));
			params.add(new NameValuePair("code", code));
		}
		params.add(new NameValuePair("usercode", ""));
		params.add(new NameValuePair("email", ""));
		params.add(new NameValuePair("bidirection", ""));
		boolean isChanged = false;
		try {
			String html = client.doPost(url, ADD_URL, params.toArray(new NameValuePair[]{})).getContent();
			if (html.indexOf("好友请求已发送成功!") > -1) {
				user.addStep(RegStep.ADD_FRIEND_REQUEST);
				System.out.println("Add friend " + user.getId());
				isChanged = true;
			} else {
				flag = 2;
				Pattern p = Pattern.compile("var flag = parseInt[(]\"(\\d+?)\"[)];");
				Matcher m = p.matcher(html);
				if (m.find()) {
					flag = Integer.parseInt(m.group(1));
				}
			}
		} finally {
			if (isChanged) {
				KXUtil.saveUsers(users);
			}
		}
		return flag;
	}
}
